#region Using directives
using System;
using SharpWind.Resources.Meshes;
using SharpWind.Math;
using SharpWind.Resources.Shaders;
using SharpWind.Resources.Textures;
using Microsoft.DirectX.Direct3D;
using SharpWind.Graphics;
#endregion

namespace SharpWind.Scene
{
	public class StaticObject : SceneObject
	{
		#region Fields

		private SharpWind.Resources.Meshes.Mesh mesh = null;

		private SharpWind.Resources.Textures.Texture normalTexture = null;

		private SharpWind.Resources.Textures.Texture diffuseTexture = null;

		private bool normalMapping = false;

		#endregion

		#region Constructor

		public StaticObject( string name )
		{
			if( string.IsNullOrEmpty( name ) )
			{
				throw new ArgumentNullException( "name" );
			}

			this.mesh = Engine.Instance.Meshes.Load( name );
			this.boundingBox = BoundingBox.ComputeFromMesh( mesh );
			this.boundingSphere = BoundingSphere.ComputeFromMesh( mesh );
			this.normalMapping = false;
		}

		public StaticObject( string name, string diffuseTexture, string normalTexture ) : this( name )
		{
			if( string.IsNullOrEmpty( normalTexture ) )
			{
				throw new ArgumentNullException( "normalTexture" );	
			}

			if( string.IsNullOrEmpty( diffuseTexture ) )
			{
				throw new ArgumentNullException( "diffuseTexture" );
			}

			this.diffuseTexture = Engine.Instance.Textures.Load( diffuseTexture );
			this.normalTexture	= Engine.Instance.Textures.Load( normalTexture );
			this.mesh.DxMesh	=
				this.mesh.DxMesh.Clone( MeshFlags.Managed, VertexDeclarations.NormalMapping.GetDeclaration(), Engine.Instance.Graphics.Device );
			this.mesh.DxMesh.ComputeTangentFrame( 0 );
			this.normalMapping = true;
		}

		#endregion

		#region Methods

		internal override void Render( Shader shader )
		{
			if( normalMapping )
			{
				shader.SetValue( "normalTexture", this.normalTexture );
			}

			if( this.diffuseTexture != null )
			{
				shader.SetValue( "diffuseTexture", this.diffuseTexture );
				shader.Commit();
				for( int i = 0; i < this.mesh.Materials.Length; i++ )
				{
					this.mesh.DxMesh.DrawSubset( i );
				}
			}
			else
			{
				for( int i = 0; i < this.mesh.Materials.Length; i++ )
				{
					shader.SetValue( "diffuseTexture", this.mesh.Textures[i] );
					shader.Commit();
					this.mesh.DxMesh.DrawSubset( i );
				}
			}
		}

		#endregion

		#region Properties
		
		internal bool NormalMapping
		{
			get
			{
				return this.normalMapping;
				
			}	
		}

		#endregion
	}
}